using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using EstimateTracker.DataAccess.Repositories;
using EstimateTracker.Domain.Entities;
using EstimateTracker.Events;
using JetBrains.Annotations;
using Microsoft.Practices.Prism.Events;

namespace EstimateTracker.ViewModels
{
    public class ActivityViewModel : ViewModelBase
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly IActivityRepository _activityRepository;
        private readonly ObservableCollection<Activity> _activities;
        private Activity _selectedActivity;

        public ActivityViewModel([NotNull] IEventAggregator eventAggregator,[NotNull] IActivityRepository activityRepository)
        {
            if (eventAggregator == null) throw new ArgumentNullException("eventAggregator");
            if (activityRepository == null) throw new ArgumentNullException("activityRepository");

            _eventAggregator = eventAggregator;
            _activityRepository = activityRepository;

            _activities = new ObservableCollection<Activity>();
        }

        public ObservableCollection<Activity> Activities
        {
            get { return _activities; }
        }

        public Activity SelectedActivity
        {
            get { return _selectedActivity; }
            set
            {
                _selectedActivity = value;
                _eventAggregator.GetEvent<ActivitySelectedEvent>().Publish(_selectedActivity != null ? (int?)_selectedActivity.Id: null);
                OnPropertyChanged("SelectedActivity");
            }
        }

        private void Bind(int id)
        {
            Activities.Clear();
            List<Activity> activities = _activityRepository.FindByProjectId(id).ToList();
            activities.ForEach(Activities.Add);
            SelectedActivity = activities.FirstOrDefault();
        }

        public void Initialize()
        {
            DisplayActivitiesEvent displayActivitiesEvent = _eventAggregator.GetEvent<DisplayActivitiesEvent>();
            displayActivitiesEvent.Subscribe(Bind);
        }

        public void AddActivity(string activityName, Project selectedProject)
        {
            Activity activity = new Activity{Name = activityName, Project = selectedProject};
            Activities.Add(activity);
            _activityRepository.Save(activity);
        }
    }
}